package com.flyco.modules.quartz.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.modules.oms.entity.OmsOrderSetting;
import com.flyco.modules.oms.service.IOmsOrderService;
import com.flyco.modules.oms.service.IOmsOrderSettingService;
import com.flyco.modules.task.service.SapTaskService;
import io.swagger.models.auth.In;
import org.apache.shiro.authz.annotation.RequiresRoles;
import com.flyco.common.api.vo.Result;
import com.flyco.common.constant.CommonConstant;
import com.flyco.common.exception.FlycoException;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.util.ImportExcelUtil;
import com.flyco.modules.quartz.entity.QuartzJob;
import com.flyco.modules.quartz.service.IQuartzJobService;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 定时任务在线管理
 * @Version:V1.0
 */
@RestController
@RequestMapping("/f/sys/quartzJob")
@Slf4j
@Api(tags = "定时任务接口")
public class QuartzJobController {
    @Autowired
    private IQuartzJobService quartzJobService;
    @Resource
    private SapTaskService sapTaskService;
    @Autowired
    private IOmsOrderService omsOrderService;
    @Autowired
    private IOmsOrderSettingService omsOrderSettingService;

    @AutoLog
    @GetMapping("/to-sap/updateStockSH")
    @ApiOperation("更新上海飞科商品库存")
    public Result updateStockSH() {
        sapTaskService.toSapStock(1000L);
        return Result.ok();
    }

    @AutoLog
    @GetMapping("/to-sap/updateStockWZ")
    @ApiOperation("更新温州飞科商品库存")
    public Result updateStockWZ() {
        sapTaskService.toSapStock(4100L);
        return Result.ok();
    }

    @AutoLog
    @GetMapping("/to-sap/sendPickUpMsg")
    @ApiOperation("发送物流提货短信通知")
    public Result sendPickUpMsg() {
        omsOrderService.sendPickupMsg();
        return Result.ok();
    }

    @AutoLog
    @GetMapping("/to-sap/sendOrderAuditMsg")
    @ApiOperation("发送跟单员审核短信通知")
    public Result sendOrderAuditMsg() {
        omsOrderService.sendOrderAuditMsg();
        return Result.ok();
    }

    @AutoLog
    @GetMapping("/to-sap/updateStoreProductPrice")
    @ApiOperation("更新经销商可售商品范围和价格")
    public Result getSapProductPrice(Long partnerId, String storeId) {
        Long partner = 4100L;
        if (partnerId != null) {
            partner = partnerId;
        }
        sapTaskService.getSapProductPrice(partner, storeId);
        return Result.ok();
    }

    @AutoLog
    @GetMapping("/to-sap/updateBalance")
    @ApiOperation("更新经销商余额")
    public Result updateBalance(String storeId) {
        sapTaskService.updateBalance(storeId);
        return Result.ok();
    }

    @AutoLog
    @GetMapping("/to-sap/pushOrderToSap")
    @ApiOperation("检查经销商余额符合订单条件推送sap")
    public Result pushOrderToSap() {
        sapTaskService.pushOrderToSap();
        return Result.ok();
    }

    @AutoLog
    @GetMapping("/to-sap/getStatement")
    @ApiOperation("获取经销商对账单")
    public Result getStatement(Long partnerId, String storeId, String year, String month) {
        Long partner = 4100L;
        if (partnerId != null) {
            partner = partnerId;
        }
        sapTaskService.getStatement(partner, storeId, year, month);
        return Result.ok();
    }

    @AutoLog
    @GetMapping("/to-sap/order")
    @ApiOperation("推送sap订单")
    public Result toSapOrder(String orderId) {
        OmsOrderSetting orderSetting = omsOrderSettingService.getOne();
        if (orderSetting != null && orderSetting.getToSapFlag() == 1) {
            sapTaskService.toSapOrder(null, orderId, "system");
        }
        return Result.ok();
    }

    @AutoLog
    @PostMapping("/to-sap/cancelOrder")
    @ApiOperation("反审核sap订单")
    public Result toSapOrderCancel(String orderId) {
        OmsOrderSetting orderSetting = omsOrderSettingService.getOne();
        if (orderSetting != null && orderSetting.getToSapFlag() == 1) {
            sapTaskService.toSapOrderCancel(orderId);
        }
        return Result.ok();
    }

    @AutoLog
    @PostMapping("/to-sap/closeOrder")
    @ApiOperation("sap订单结案")
    public Result toSapOrderClose(String orderId) {
        boolean result = sapTaskService.closeOrder(orderId);
        if (result) {
            Result.ok("结案成功");
        }
        return Result.error("结案失败");
    }

    @AutoLog
    @PostMapping("/to-sap/revokeCloseOrder")
    @ApiOperation("sap订单反结案")
    public Result revokeCloseOrder(String orderId) {
        sapTaskService.revokeCloseOrder(null);
        return Result.ok();
    }

    @AutoLog
    @GetMapping("/to-sap/updateDealerDiscount")
    @ApiOperation("更新经销商折扣信息")
    public Result updateDealerDiscount(Long partnerId) {
        Long partner = 4100L;
        if (partnerId != null) {
            partner = partnerId;
        }
        sapTaskService.updateDealerDiscount(partner, "");
        return Result.ok();
    }

    @AutoLog
    @GetMapping("/to-sap/autoOrderCancel")
    @ApiOperation("订单初审后超时未复审自动取消订单")
    public Result autoOrderCancel() {
        sapTaskService.autoOrderCancel();
        return Result.ok();
    }

    @AutoLog
    @GetMapping("/to-sap/updateOutStockStatus")
    @ApiOperation("更新交货单状态")
    public Result updateOutStockStatus(Long partnerId, String orderId) {
        Long partner = 4100L;
        if (partnerId != null) {
            partner = partnerId;
        }
        sapTaskService.updateOutStockStatus(partner, orderId);
        return Result.ok();
    }

    @AutoLog
    @GetMapping("/to-sap/updateStoreDisabledStatus")
    @ApiOperation("更新经销商手工禁用状态")
    public Result updateStoreDisabledStatus(String storeId) {
        sapTaskService.updateStoreDisabledStatus(storeId);
        return Result.ok();
    }


    /**
     * 分页列表查询
     *
     * @param quartzJob
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<?> queryPageList(QuartzJob quartzJob, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        QueryWrapper<QuartzJob> queryWrapper = QueryGenerator.initQueryWrapper(quartzJob, req.getParameterMap());
        Page<QuartzJob> page = new Page<QuartzJob>(pageNo, pageSize);
        IPage<QuartzJob> pageList = quartzJobService.page(page, queryWrapper);
        return Result.ok(pageList);

    }

    /**
     * 添加定时任务
     *
     * @param quartzJob
     * @return
     */
    @RequiresRoles("admin")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<?> add(@RequestBody QuartzJob quartzJob) {
        List<QuartzJob> list = quartzJobService.findByJobClassName(quartzJob.getJobClassName());
        if (list != null && list.size() > 0) {
            return Result.error("该定时任务类名已存在");
        }
        quartzJobService.saveAndScheduleJob(quartzJob);
        return Result.ok("创建定时任务成功");
    }

    /**
     * 更新定时任务
     *
     * @param quartzJob
     * @return
     */
    @RequiresRoles("admin")
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Result<?> eidt(@RequestBody QuartzJob quartzJob) {
        try {
            quartzJobService.editAndScheduleJob(quartzJob);
        } catch (FlycoException e) {
            log.error(e.getMessage(), e);
            return Result.error("更新定时任务失败!");
        }
        return Result.ok("更新定时任务成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @RequiresRoles("admin")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        QuartzJob quartzJob = quartzJobService.getById(id);
        if (quartzJob == null) {
            return Result.error("未找到对应实体");
        }
        quartzJobService.deleteAndStopJob(quartzJob);
        return Result.ok("删除成功!");

    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @RequiresRoles("admin")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        }
        for (String id : Arrays.asList(ids.split(","))) {
            QuartzJob job = quartzJobService.getById(id);
            quartzJobService.deleteAndStopJob(job);
        }
        return Result.ok("删除定时任务成功!");
    }

    /**
     * 暂停定时任务
     *
     * @param jobClassName
     * @return
     */
    @RequiresRoles("admin")
    @GetMapping(value = "/pause")
    @ApiOperation(value = "暂停定时任务")
    public Result<Object> pauseJob(@RequestParam(name = "jobClassName", required = true) String jobClassName) {
        QuartzJob job = null;
        try {
            job = quartzJobService.getOne(new LambdaQueryWrapper<QuartzJob>().eq(QuartzJob::getJobClassName, jobClassName));
            if (job == null) {
                return Result.error("定时任务不存在！");
            }
            quartzJobService.pauseJob(job);
        } catch (FlycoException e) {
            throw new FlycoException("暂停定时任务失败");
        }
        job.setStatus(CommonConstant.STATUS_DISABLE);
        quartzJobService.updateById(job);
        return Result.ok("暂停定时任务成功");
    }

    /**
     * 启动定时任务
     *
     * @param jobClassName
     * @return
     */
    @RequiresRoles("admin")
    @GetMapping(value = "/resume")
    @ApiOperation(value = "恢复定时任务")
    public Result<Object> resumeJob(@RequestParam(name = "jobClassName", required = true) String jobClassName) {
        QuartzJob job = quartzJobService.getOne(new LambdaQueryWrapper<QuartzJob>().eq(QuartzJob::getJobClassName, jobClassName));
        if (job == null) {
            return Result.error("定时任务不存在！");
        }
        quartzJobService.resumeJob(job);
        //scheduler.resumeJob(JobKey.jobKey(job.getJobClassName().trim()));
        return Result.ok("恢复定时任务成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        QuartzJob quartzJob = quartzJobService.getById(id);
        return Result.ok(quartzJob);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param quartzJob
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, QuartzJob quartzJob) {
        // Step.1 组装查询条件
        QueryWrapper<QuartzJob> queryWrapper = QueryGenerator.initQueryWrapper(quartzJob, request.getParameterMap());
        // Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new EntityExcelView());
        List<QuartzJob> pageList = quartzJobService.list(queryWrapper);
        // 导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "定时任务列表");
        mv.addObject(NormalExcelConstants.CLASS, QuartzJob.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("定时任务列表数据", "导出人:FlyCo", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 错误信息
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<Object> listQuartzJobs = ExcelImportUtil.importExcel(file.getInputStream(), QuartzJob.class, params);
                List<String> list = ImportExcelUtil.importDateSave(listQuartzJobs, IQuartzJobService.class, errorMessage, CommonConstant.SQL_INDEX_UNIQ_JOB_CLASS_NAME);
                errorLines += list.size();
                successLines += (listQuartzJobs.size() - errorLines);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
    }
}
